<?php
require_once  SzSystem::$FRAME_ROOT . '/vendor/sina/WeiyouxiApi.php';

class ModuleSnsSina extends ModuleSns
{
    /**
     * @var WeiyouxiApi $sdk
     */
    protected $sdk;
    /**
     * @var int $platformId
     */
    protected $platformId;

    /**
     * @see ModuleSns::__construct()
     */
    public function __construct($userId, $platform, $configs)
    {
        /**
         * array(
         *     'appId' => array('key' => 'appId', 'value' => ...),
         *     'appSecret' => array('key' => 'appSecret', 'value' => ...),
         *     'appToken' => array('key' => 'appToken', 'value' => ...),
         *     'payToken' => array('key' => 'payToken', 'value' => ...),
         * )
         *
         * @var array $configs
         */
        parent::__construct($userId, $platform, $configs);

        $this->sdk = new WeiyouxiApi($this->configs['appId']['value'] , $this->configs['appSecret']['value']);

        // 重新验证token
        $pfToken = $this->getPfToken();
        $pfSignature = $this->getPfSignature();
        if ($pfToken && $pfSignature) {
            $this->sdk->setSignature($pfSignature);
            $this->sdk->setSessionKey($pfToken);
            $this->sdk->checkSessionKey();
        }
    }

    /**
     * @see ModuleSns::createJsEmbededCode()
     */
    public function createJsEmbeddedCode()
    {
        return
"
<script type='text/javascript'
    src='//game.weibo.com/static/js/v0.3/wyx.connect.js.php'>
</script>
<script>
    WYX.Connect.init();
</script>
";
    }

    /**
     * @see ModuleSns::getPfToken()
     */
    public function getPfToken()
    {
        return SzParam::getReqParam('wyx_session_key');
    }

    /**
     * @see ModuleSns::getPfSignature()
     */
    public function getPfSignature()
    {
        return SzParam::getReqParam('wyx_signature');
    }

    /**
     * @see ModuleSns::initializeOnIndex()
     */
    public function initializeOnIndex()
    {
        return array($this->userId, ModuleSnsConst::PFSA);
    }

    /**
     * 读取玩家信息
     *
     * @param string $platformId
     * @return array
     * <pre>
     *  SUCCEED:
     *  {
            "id": 1905734003,                  //用户UID
            "idstr": "1905734003",
            "screen_name": "BRYAN_NYD",        //微博昵称
            "name": "BRYAN_NYD",               //显示名称，同微博昵称
            "province": "41",                  //省份编码（参考省份编码表）[附加信息栏目内]
            "city": "12",                      //省份编码（参考省份编码表）[附加信息栏目内]
            "location": "河南 三门峡",           //地址
            "description": "喜欢 有山玩水贴近 等大自然的感觉",                 //个人描述
            "url": "http://blog.sina.com.cn/nyd891022",                     //用户博客地址
            "profile_image_url": "http://tp4.sinaimg.cn/1905734003/50/5608743241/1",   //自定义图像 ( 50*50 )
            "domain": "nyd891022",              //用户个性化URL
            "gender": "m",                      //性别,m--男，f--女,n--未知
            "followers_count": 371,             //粉丝数
            "friends_count": 290,               //关注数
            "statuses_count": 81,               //微博数
            "favourites_count": 0,              //收藏数
            "created_at": "Wed Dec 29 00:00:00 +0800 2010",                 //创建时间
            "following": false,
            "allow_all_act_msg": false,
            "geo_enabled": true,
            "verified": false,                  //加V标示，是否是微博加V认证用户
            "verified_type": 0,                 //表示加V 和达人的类 型，关系为：0- 名人；1-政府；2-企业；3-媒 体；4-校园；5-网站；6-应用 ; 7-团体（机构）;
            "allow_all_comment": true,
            "avatar_large": "http://tp4.sinaimg.cn/1905734003/180/5608743241/1",   //自定义图像 ( 180*180 )
            "verified_reason": "",
            "follow_me": false,
            "online_status": 0,
            "bi_followers_count": 261,
            "lang": "zh-cn",
            "status_id": 1615643123,
            "achievements_count": 0,            // 用户获得的总成就数
            "games_count": 2,                   //  用户安装的游戏数
            "identity_status" :2                // 0-未认证 1-认证未满18 2-认证满18
            "vip_level" : 0                     //微游戏VIP等级
     * }
     * ------------------------
     * FIELD:
     * {
            "request":"",       //调用地址
            "error_code":"400", //错误代码
            "error":"",         //错误信息
     * }
     * </pre>
     */
    public function getUserInfo($platformId)
    {
        $params = array(
            'uid' => $platformId
        );

        $data = $this->sdk->get('user/show', $params);
        if (!SzUtility::checkArrayKey('error_code', $data)) {
            return $data;
        } else {
            return array();
        }
    }


    /**
     * 读取玩家信息
     *
     * @param array $platformId
     * @return array
     * <pre>
     *  SUCCEED:
     *  {
            "1905734003": {
                "id": 1905734003,
                "idstr": "1905734003",
                "screen_name": "BRYAN_NYD",
                "name": "BRYAN_NYD",
                "province": "41",
                "city": "12",
                "location": "河南 三门峡",
                "description": "喜欢 游山玩水 ， 珍惜光阴: [黑发不知勤学早，白首方悔读书迟 ] [一寸光阴一寸金，存金难买存光阴] [锲而舍之朽木不折；锲而不舍金石可镂]",
                "url": "http://blog.sina.com.cn/nyd891022",
                "profile_image_url": "http://tp4.sinaimg.cn/1905734003/50/5608743241/1",
                "domain": "nyd891022",
                "gender": "m",
                "followers_count": 433,
                "friends_count": 329,
                "statuses_count": 166,
                "favourites_count": 0,
                "created_at": "Wed Dec 29 00:00:00 +0800 2010",
                "following": false,
                "allow_all_act_msg": false,
                "geo_enabled": true,
                "verified": false,
                "verified_type": 220,
                "allow_all_comment": true,
                "avatar_large": "http://tp4.sinaimg.cn/1905734003/180/5608743241/1",
                "verified_reason": "",
                "follow_me": false,
                "online_status": 0,
                "bi_followers_count": 290,
                "lang": "zh-cn",
                "level": 7,
                "type": 1,
                "badge": {
                    "kuainv": {
                        "level": 0
                    },
                    "uc_domain": 0,
                    "enterprise": 0,
                    "anniversary": 1
                },
                "status_id": 7558,
            },
            ...
     * }
     * ------------------------
     * FIELD:
     * {
            "request":"",       //调用地址
            "error_code":"400", //错误代码
            "error":"",         //错误信息
     * }
     * </pre>
     */
    public function getUserInfos($platformId)
    {
        $params = array(
            'uids' => implode(',', $platformId),
            'trim_status' => 1
        );

        $data = $this->sdk->get('user/show_batch', $params);
        if (!SzUtility::checkArrayKey('error_code', $data)) {
            return $data;
        } else {
            return array();
        }
    }

    /**
     * 发微博
     *
     * @param string $platformId
     * @param string $contents
     * @param string $picUrl
     * @return array
     */
    public function sendWeibo($platformId, $contents, $picUrl)
    {
        $params = array(
            'uid' => $platformId,
            'status' => $contents,
            'pic' => $picUrl
        );
        $data = $this->sdk->post('statuses/upload', $params);
        if (!SzUtility::checkArrayKey('error_code', $data)) {
            return $data;
        } else {
            return array();
        }
    }

    /**
     * 读取玩家好友信息
     *
     * @param int $page
     * @param int $count
     * <pre>
     * SUCCEED:
     * {
            "users": [
                {
                    "id": 1080212342,
                    "screen_name": "名称",
                    "name": "，名称",
                    "profile_image_url": "http://tp3.sinaimg.cn/1080212342/50/5719556687/0",
                    "head_image_url": "http://tp3.sinaimg.cn/1080212342/180/5719556687/0"
                }, ...
            ],
            "total_number": 18
     * }
     *  -------------------
     * FIELD:
     * {
            "request":"",       //调用地址
            "error_code":"400", //错误代码
            "error":"",         //错误信息
     * }
     * </pre>
     * @return array
     */
    public function getFriends($page, $count = 0)
    {
        $params = array(
            'page' => $page,
            'count' => $count,
            'trim' => 1
        );
        $data = $this->sdk->get('user/friends', $params);
        if (!SzUtility::checkArrayKey('error_code', $data)) {
            return $data;
        } else {
            return array();
        }
    }

    /**
     * @see ModuleSns::getPfFriends()
     */
    protected function getPfFriends($userId)
    {
        return array();
    }

    /**
     * @see ModuleSns::preparePfApiEnv()
     */
    protected function preparePfApiEnv()
    {
    }

    /**
     * @see ModuleSns::checkResult()
     */
    protected function checkResult($result)
    {
    }

    /**
     * Platform fetch games player info
     *
     * @return string
     */
    public function fetchUserInfo()
    {
        /**
         * array(
         *      'SPID' => 'sina',
         *      'ServerID' => '0',
         *      'UserID' => '2146731414',
         *      'UserIP' => '0.0.0.0',
         *      'Sign' => '003669fe5d67bbf3b3653345e618cd55',
         * )
         */
        $decodedInput = SzParam::getWholeRequest();

        // 返回结构
        $return = array(
            'Code' => 0,
            'ErrorMsg' => "",
            'ServerID' => "",
            'UserID' => "",
            'GameRole' => array()
        );

        // check the decoded structure
        if (!(
            isset($decodedInput['SPID'])
            && isset($decodedInput['ServerID'])
            && isset($decodedInput['UserID'])
            && isset($decodedInput['UserIP'])
            && isset($decodedInput['Sign'])
        )) {
            $return['Code'] = 100;
            return json_encode($return);
        }

        // 更新返回值
        $return['ServerID'] = $decodedInput['ServerID'];
        $return['UserID']   = $decodedInput['UserID'];

        // 获取appToken
        $appToken   = $this->configs['appToken']['value'];

        // 验证signature是否正确
        if ($decodedInput['Sign'] != md5("SPID={$decodedInput['SPID']}&ServerID={$decodedInput['ServerID']}&UserID={$decodedInput['UserID']}&UserIP={$decodedInput['UserIP']}&key={$appToken}")) {
            $return['Code'] = 110;
            return json_encode($return);
        }

        // 验证玩家帐号是否存在
        $platformId = $decodedInput['UserID'];
        $userId = $this->portPlayerUserId($platformId);
        if (is_null($userId)) {
            $return['Code'] = 120;
            return json_encode($return);
        }

        // 验证玩家游戏角色是否创建
        $profile = SzPersister::get()->getVo($userId, ModuleProfileConst::ORM_NAME_PROFILE);
        if (is_null($profile)) {
            $return['Code'] = 121;
            return json_encode($return);
        }

        // 检查服务器维护状态
        $appConfig = SzConfig::get()->loadAppConfig('app');
        if ($appConfig['MAINTENANCE']) {
            $return['Code'] = 122;
            return json_encode($return);
        }

        // 读取并返回玩家人物信息
        /** @var ModuleProfileVo $profile */
        $return['GameRole'][] = array('RoleID' => $platformId, 'RoleName' => $platformId . ' | Lv.'.$profile->getLevel());

        return json_encode($return);
    }
}